package org.wtframework.platform.server.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.openredhead.springx.core.server.page.IPage;
import org.openredhead.springx.core.web.mvc.ajaxrpc.BasicAjaxRpcRemoteService;
import org.openredhead.springx.core.web.mvc.annotation.AjaxRpcMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wtframework.platform.server.log.SystemServiceLog;
import org.wtframework.platform.server.manager.impl.GroupManager;
import org.wtframework.platform.server.manager.impl.ResourceManager;
import org.wtframework.platform.server.manager.impl.RoleManager;
import org.wtframework.platform.server.manager.impl.UserDetailManager;
import org.wtframework.platform.server.manager.impl.UserIdentityManager;
import org.wtframework.platform.server.manager.impl.UserManager;
import org.wtframework.platform.server.model.impl.Group;
import org.wtframework.platform.server.model.impl.Resource;
import org.wtframework.platform.server.model.impl.Role;
import org.wtframework.platform.server.model.impl.User;
import org.wtframework.platform.server.model.impl.UserDetail;
import org.wtframework.platform.server.model.impl.UserIdentity;
import org.wtframework.platform.server.util.MathUtils;
import org.wtframework.platform.server.util.PropertiesUtil;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;


@Service
public class BackManagerService extends BasicAjaxRpcRemoteService {

	@Autowired
	private UserManager userManager;

	@Autowired
	private ResourceManager resourceManager;

	@Autowired
	private GroupManager groupManager;

	@Autowired
	private UserIdentityManager userIdentityManager;

	@Autowired
	private RoleManager roleManager;
	
	@Autowired
	private UserDetailManager userDetailManager;

	
	@AjaxRpcMethod
	@SystemServiceLog(description="重置密码")
	public Boolean resetPassword(Long userId){
		
		try {
			User user = userManager.load(userId);
			user.setPassword(DigestUtils.md5Hex("1"));
			userManager.save(user);
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
		
	}

	/**
	 * 
	 * <B>方法描述：</B>（删除用户列表） <br/>
	 * 
	 * <B>作者： </B> 黄杰帆 <br/>
	 * 
	 * @param idList
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="删除用户")
	public void userDelete(List<Long> idList) {
		
		List<User> users = userManager.loadList(idList);
		userManager.delete(users);
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（删除用户详细信息） <br/>
	 *
	 * <B>作者：	 </B> 何展操 <br/>
	 * <B>创建日期：</B> 2014-9-8 下午5:26:48 
	 * @param userIdList
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="删除用户详细信息")
	public void userDetailDelete(List<Long> userIdList) {
		
		String hql = "delete from UserDetail where userId in (:userIdList)";
		userDetailManager.getQuery(hql, "userIdList", userIdList).executeUpdate();
	}

	/**
	 * 
	 * <B>方法描述：</B>（添加用户） <br/>
	 * 
	 * <B>作者： </B> 黄杰帆 <br/>
	 * 
	 * @param user
	 * @throws Exception
	 */
	@SystemServiceLog(description="添加用户")
	@AjaxRpcMethod
	public boolean userAdd(User user) {

		if (userManager.find("username", user.getUsername()).getCount() > 0) {
//				throw new RuntimeException("该用户名已存在!");
				return false;
		} else {
			
			user.setPassword(DigestUtils.md5Hex(user.getPassword()));
			if(user.getIdentityId() == null) {
				UserIdentity userIdentity = userIdentityManager.getDefalutUserIdentity();
				if (userIdentity != null) {
					user.setIdentityId(userIdentity.getId());
					user.setUnableScore(userIdentity.getInitScore());
				}
			} else {
				UserIdentity userIdentity = userIdentityManager.load(user.getIdentityId());
				user.setUnableScore(userIdentity.getInitScore());
			}
			//随机生成头像
			String[] imageArray = new String[]{"tou_a.jpg", "tou_b.jpg", "tou_c.jpg", "tou_d.jpg", "tou_e.jpg", "tou_f.jpg", "tou_g.jpg", "tou_h.jpg"};
			Random rand = new Random();
			Integer tem = rand.nextInt(8);
			String imagestr = "/style/back/image/" + imageArray[tem];
			user.setImageUrl(imagestr);
			userManager.save(user);
		}
		return true;

	}

	/**
	 * 
	 * <B>方法描述：</B>（更新用户） <br/>
	 * 
	 * <B>作者： </B> 黄杰帆 <br/>
	 * 
	 * @param user
	 * @throws Exception
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="更新用户")
	public boolean userUpdate(User user) {
		User updateUser = userManager.load(user.getId());
		int count = userManager.findByQuery("from User u where u.username = ? and u.id != ? ", new Object[] { user.getUsername(), user.getId() }).getCount();
		if (count > 0) {
//			throw new RuntimeException("该用户名已存在!");
			return false;
		} else {
			updateUser.setUsername(user.getUsername());
			updateUser.setNickname(user.getNickname());
			updateUser.setIdentityId(user.getIdentityId());
			updateUser.setEmail(user.getEmail());
			updateUser.setPhoneNumber(user.getPhoneNumber());
			if(!Strings.isNullOrEmpty(user.getPassword())){
				updateUser.setPassword(DigestUtils.md5Hex(user.getPassword()));
			}
			userManager.save(updateUser);
		}
		return true;
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（更新用户详细信息） <br/>
	 *
	 * <B>作者：	 </B> 何展操 <br/>
	 * <B>创建日期：</B> 2014-9-5 下午3:39:04 
	 * @param hql
	 * @param values
	 * @return
	 */
	@SystemServiceLog(description="更新用户详细信息")
	public int growUserUpdate(Object[] userValues, Object[] userDetailValues) {
		int result = -1;
		if (updateUserTable(userValues) >0 && updateUserDetail(userDetailValues) >0) {
			result=1;
		}
		return result;
	}
	@SystemServiceLog(description="更新用户信息")
	public int updateUserTable(Object[] userValues){
		String hqlUSer = "update from User set imageUrl=?, nickname=?, phoneNumber=? where id=? and username=?";
		 return userManager.getQuery(hqlUSer, userValues).executeUpdate();
	}
	@SystemServiceLog(description="更新用户详细信息")
	public int updateUserDetail(Object[] userDetailValues){
		String hqlUserDetail = "update from UserDetail set gender=?, telephoneNumber=? where userId=?";
		return userDetailManager.getQuery(hqlUserDetail, userDetailValues).executeUpdate();
	}
	@SystemServiceLog(description="增加用户详细信息")
	public void addUserDetail(Long userId){
		
		try {
			if(userId != null){
				UserDetail userDetail=findUserDetailByUserId(userId);
				if(userDetail == null){
					UserDetail updateUserDetail=new UserDetail();
					updateUserDetail.setUserId(userId);
					userDetailManager.save(updateUserDetail);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（获取身份下角色列表） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param groupId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@AjaxRpcMethod
//	@SystemServiceLog(description="获取身份下角色列表")
	public List<Role> getUserIdentityRoles(Integer userIdentityId) {

		List<Role> roleList = Lists.newArrayList();
		if(userIdentityId !=null) {
			UserIdentity userIdentity = userIdentityManager.load(userIdentityId);
			if(userIdentity != null) {
				List<Integer> roleIds = userIdentity.getRolesId();
				if(roleIds.size() != 0) {
					String hql = "from Role where id in (:idList)";
					roleList = roleManager.getQuery(hql).setParameterList("idList", roleIds).list();
				}
			}
		}
		return roleList;
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（获取用户的组下角色列表） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param groupId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@AjaxRpcMethod
//	@SystemServiceLog(description="获取用户组下角色列表")
	public List<Role> getUserGroupRoles(Integer groupId) {
		
		List<Role> roleList = Lists.newArrayList();
		if(groupId !=null) {
			Group group = groupManager.load(groupId);
			if(group != null) {
				List<Integer> roleIds = group.getRolesId();
				if(roleIds.size() != 0) {
					String hql = "from Role where id in (:idList)";
					roleList = roleManager.getQuery(hql).setParameterList("idList", roleIds).list();
				}
			}
		}
		return roleList;
	}

	/***
	 * 
	 * <B>方法描述：</B>（用户分配角色） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param userId
	 * @param roleIdList
	 */
	@SuppressWarnings("unchecked")
	@AjaxRpcMethod
	@SystemServiceLog(description="分配用户角色")
	public void userAllotRole(Long userId, List<Integer> roleIdList) {

		User user = userManager.load(userId);
		List<Integer> rolesId = Lists.newArrayList();
		if(roleIdList != null && roleIdList.size() != 0) {	
			String hql = "from Role where id in (:idList)";
			List<Role> roleList = roleManager.getQuery(hql).setParameterList("idList", roleIdList).list();
			
			for (Role role : roleList) {
				rolesId.add(role.getId());
			}
		}

		user.setRolesId(rolesId);
		userManager.save(user);
	}

	/***
	 * 
	 * <B>方法描述：</B>（获取所有用户的角色权限） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param roleId
	 * @param resourceIdList
	 */
	@SuppressWarnings("unchecked")
	@AjaxRpcMethod
//	@SystemServiceLog(description="获取所有用户的角色权限")
	public List<Resource> loadUserRolesResources(Long userId) {

		User user = userManager.load(userId);
		Set<Role> roleSet = Sets.newConcurrentHashSet(); // 用户的所有角色
		Set<Integer> roleIdsSet = Sets.newConcurrentHashSet(); // 用户的所有角色id
		Set<Integer> resourceSet = Sets.newConcurrentHashSet(); // 用户的所有权限

		String hql = "from Role where id in (:idList)";
		if (user.getRolesId().size() != 0) {
			roleSet.addAll(roleManager.getQuery(hql).setParameterList("idList", user.getRolesId()).list());
		}
		if(user.getParentId() != null) {
			Group group = groupManager.load(user.getParentId());
			if(group != null && group.getRolesId().size() != 0) {
				roleIdsSet.addAll(group.getRolesId());
			}
		}
		if(user.getIdentityId() != null) {
			UserIdentity userIdentity = userIdentityManager.load(user.getIdentityId());
			if(userIdentity != null && userIdentity.getRolesId().size() != 0) {
				roleIdsSet.addAll(userIdentity.getRolesId());
			}
		}
		if(roleIdsSet.size() != 0) {
			hql = "from Role where id in (:idList)";
			roleSet.addAll(roleManager.getQuery(hql).setParameterList("idList", roleIdsSet).list());
		}
		for (Role role : roleSet) {
			resourceSet.addAll(role.getResourcesId());
		}
		if (resourceSet.size() == 0) { return new ArrayList<Resource>(); }
		hql = "from Resource where id in (:idList)";
		return resourceManager.getQuery(hql).setParameterList("idList", resourceSet).list();
	}

	/***
	 * 
	 * <B>方法描述：</B>（用户分配权限资源） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 此方法暂时未用上
	 * 
	 * @param userId
	 * @param resourceIdList
	 */
	@AjaxRpcMethod
	public void userAllotResource(Long userId, List<Integer> resourceIdList) {

	}

	/**
	 * 
	 * <B>方法描述：</B>（获取职能部门列表） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
	@AjaxRpcMethod
//	@SystemServiceLog(description="获取职能部门列表")
	public List<Group> getGroupList(Integer sortId) {

		if (sortId == null) {
			sortId = 1;
		}
		return groupManager.find("orderId", true, "sortId", sortId).getList();
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（获取根职能部门列表） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
	@AjaxRpcMethod
//	@SystemServiceLog(description="获取根职能部门列表")
	public List<Group> getRootGroupList(Integer sortId) {
		
		if (sortId == null) {
			sortId = 1;
		}
		return groupManager.find("orderId", true, new String[]{"sortId", "parentId"}, sortId, null).getList();
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（获取班级列表） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
//	@SystemServiceLog(description="获取班级列表")
	public List<Group> getClassList() {
		
		String queryString = "from Group where sortId = ? and parentId != null order by parentId asc, orderId asc";
		return groupManager.findByQuery(queryString, 2).getList();
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（获取所有班级名及id） <br/>
	 *
	 * <B>作者：	 </B> 何展操 <br/>
	 * <B>创建日期：</B> 2014年12月5日 下午3:23:07 
	 * @return
	 */
//	@SystemServiceLog(description="获取所有班级名及Id")
	public Map<Integer, String> getAllGroupIdAndName(){
		Map<Integer, String> groupMap = Maps.newHashMap();
		List<Group> groupList = getClassList();
		for(Group group : groupList){
			groupMap.put(group.getId(), group.getName());
		}
		return groupMap;
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（职能部门添加方法） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="添加职能部门")
	public void groupAdd(Group group) {
		try {
			group.setEstablishDate(new Date());
			groupManager.save(group);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * <B>方法描述：</B>（职能部门更新方法） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="更新职能部门")
	public void groupUpdate(Group group) {
		try {
			Group tmpGroup = groupManager.load(group.getId());
			//tmpGroup.setParentId(group.getParentId());
			tmpGroup.setName(group.getName());
			tmpGroup.setDescn(group.getDescn());
			groupManager.save(tmpGroup);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * <B>方法描述：</B>（职能部门删除方法） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="删除职能部门")
	public void groupDelete(Integer id) {
		
		List<Integer> ids = groupManager.getSortAndAllChildIds(id);
		String hql = "update User set parentId=null where parentId in (:parentIdList)";
		userManager.getQuery(hql, "parentIdList", ids).executeUpdate();
		List<Group> groups = groupManager.loadList(ids);
		groupManager.delete(groups);

	}
	
	/**
	 * 
	 * <B>方法描述：</B>（找出部门信息方法） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
//	@SystemServiceLog(description="查看部门信息")
	public Group findGroup(Integer id) {
		
		return groupManager.load(id);
	}

	/***
	 * 
	 * <B>方法描述：</B>（部门分配角色） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param groupId
	 * @param roleIdList
	 */
	@SuppressWarnings("unchecked")
	@AjaxRpcMethod
	@SystemServiceLog(description="分配部门角色")
	public void groupAllotRole(Integer groupId, List<Integer> roleIdList) {

		List<Integer> groupIds = groupManager.getSortAndAllChildIds(groupId);
		String hql = "from Group where id in (:idList)";
		List<Group> groups = groupManager.getQuery(hql).setParameterList("idList", groupIds).list();
		for (Group group : groups) {
			group.setRolesId(roleIdList);
			groupManager.save(group);
		}

	}

	/**
	 * 
	 * <B>方法描述：</B>（获取权限资源列表） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
//	@SystemServiceLog(description="获取权限资源列表")
	public List<Resource> getResourceList() {
		return resourceManager.loadAll("orderId", true).getList();
	}

	@AjaxRpcMethod
	public Map<Integer,Resource> getResourceMap() {

		String showId = PropertiesUtil.readUrl("sys.path.has.showId");
		
		Map<Integer,Resource> map = Maps.newHashMap();
		
		List<Resource> list = Lists.newArrayList();
		
		list = resourceManager.findByQuery("from Resource where showId=? order by orderId",Integer.valueOf(showId)).getList();
		
		for(Resource r : list){
			map.put(r.getId(), r);
		}
		
		return map;
	}

	
	/**
	 * 
	 * <B>方法描述：</B>（获取权限资源添加方法） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="添加权限资源")
	public Boolean resourceAdd(Resource resource) {
		Resource resource1 = resourceManager.findUnique("identifier",resource.getIdentifier());
		if(resource1!=null){
			return 	false;
			}else{
					resourceManager.save(resource);
					return true;
		          }
	
	}

	/**
	 * 
	 * <B>方法描述：</B>（获取权限资源更新方法） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="更新权限资源")
	public void resourceUpdate(Resource resource) {

		Resource tmpResource = resourceManager.load(resource.getId());
		tmpResource.setUrl(resource.getUrl());
		tmpResource.setName(resource.getName());
		tmpResource.setIdentifier(resource.getIdentifier());
		tmpResource.setMethod(resource.getMethod());
		tmpResource.setMenuUrl(resource.getMenuUrl());
		tmpResource.setSensitivity(resource.getSensitivity());
		tmpResource.setDescn(resource.getDescn());
		resourceManager.save(tmpResource);
	}

	/**
	 * 
	 * <B>方法描述：</B>（权限资源删除方法） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="删除权限资源")
	public void resourceDelete(Integer id) {

		resourceManager.deleteSortAndAllChildIds(id);
	}

	/**
	 * 
	 * <B>方法描述：</B>（用户身份添加） <br/>
	 * 
	 * <B>作者： </B> 黄杰帆 <br/>
	 * 
	 * @param userIdentity
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="添加用户身份")
	public void userIdentityAdd(UserIdentity userIdentity) {
		userIdentityManager.save(userIdentity);
	}

	@AjaxRpcMethod
	@SystemServiceLog(description="更新用户身份")
	public void userIdentityUpdate(UserIdentity userIdentity) {

		UserIdentity tempUserIdentity = userIdentityManager.load(userIdentity.getId());
		tempUserIdentity.setName(userIdentity.getName());
		tempUserIdentity.setDescn(userIdentity.getDescn());
		tempUserIdentity.setIdentifier(userIdentity.getIdentifier());
		tempUserIdentity.setInitScore(userIdentity.getInitScore());
		tempUserIdentity.setRolesId(userIdentity.getRolesId());
		userIdentityManager.save(tempUserIdentity);
	}

	/***
	 * 
	 * <B>方法描述：</B>（删除用户身份） <br/>
	 * 
	 * <B>作者： </B> 黄杰帆 <br/>
	 * 
	 * @param idList
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="删除用户身份")
	public void userIdentityDelete(List<Integer> idList) {
		
		List<UserIdentity> userIdentitys = userIdentityManager.loadList(idList);
		userIdentityManager.delete(userIdentitys);
	}
	
	
	/**
	 * 
	 * <B>方法描述：</B>（加载最新空间） <br/>
	 *
	 * <B>作者：	 </B> 何展操 <br/>
	 * <B>创建日期：</B> 2014-9-12 上午11:10:40 
	 * @param pageNo
	 * @param pageSize
	 * @param parameNames
	 * @param queryString
	 * @param values
	 * @return
	 */
	public IPage<Map<String, Object>> findUserPropertyList(Integer pageNo, Integer pageSize, String[] parameNames, String queryString, Object... values){
		return userManager.findProperty(parameNames, queryString, values).getPageByPageNo(pageNo, pageSize);
	}
	
     @SuppressWarnings("unchecked")
     @SystemServiceLog(description="加载最新空间")
	public List<Object[]> findUserProperty(Integer pageNo, Integer pageSize, String[] parameNames, String queryString, Object... values){
		
		//System.out.println(queryString);
		List<Object[]> resultList = userManager.getSQLQuery(queryString).setFirstResult(0).setMaxResults(3).list();
		return resultList;
		//return userManager.findProperty(parameNames, queryString, values).getPageByPageNo(pageNo, pageSize);
	}
	
	public List<Map<String, Object>> findHotUserPropertyList(Integer resultNum, String parames){

		String pm4 = "(select count(*) from nzsz_zone_concerned c where e.id = c.follower_id),";
		String sql = "select " + pm4 + parames + " from orh_sx_user e ";
		sql+= "where e.locked =0 and e.id>2 order by 1 desc";
		List<Map<String, Object>> userMapList = Lists.newArrayList();
		@SuppressWarnings("unchecked")
		List<Object[]> list = userManager.getSQLQuery(sql).list();
		Integer len = list.size();
		Integer totalUserNum = userManager.loadAll().getCount();
		if(len >resultNum){
			len = resultNum;
		}
		String[] paramesName = parames.split(",");
		for(int i=0; i<paramesName.length; i++){
			String str = paramesName[i];
			str=str.substring(str.indexOf(".")+1, str.length());
			paramesName[i] = str;
		}
		
		for(int i=0; i<len; i++){
			
			Map<String, Object> map = Maps.newHashMap();
			Object[] oArray = list.get(i);
			Double num = 0.0;
			if(oArray[0]!=null){
				num = Double.valueOf(oArray[0].toString());
			}
			Double hotDegree = 0.0;
			if(totalUserNum!=0){
				hotDegree = num/totalUserNum;
			}
			String hotResult = MathUtils.saveMathPointerStr(1, 1, 1, hotDegree);
			map.put("hotDegree", hotResult);
			for(int j=0; j<paramesName.length; j++){
				map.put(paramesName[j],(Object)(oArray[j+1]));
			}
			
			userMapList.add(map);
			
		}
		return userMapList;
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（获取所有身份列表） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @return
	 */
	@AjaxRpcMethod
//	@SystemServiceLog(description="获取用户身份列表")
	public List<UserIdentity> getUserIdentityList() {

		return userIdentityManager.loadAll("orderId", true).getList();
	}

	/***
	 * 
	 * <B>方法描述：</B>（身份分配角色） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param userIdentityId
	 * @param roleIdList
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="分配角色身份")
	public void userIdentityAllotRole(Integer userIdentityId, List<Integer> roleIdList) {

		UserIdentity userIdentity = userIdentityManager.load(userIdentityId);
		userIdentity.setRolesId(roleIdList);
		userIdentityManager.save(userIdentity);
	}

	/***
	 * 
	 * <B>方法描述：</B>（设置为默认身份） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param userIdentityId
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="设置默认身份")
	public void setDefaultUserIdentity(Integer userIdentityId) {

		String hql = "update UserIdentity set isDefault = ? where isDefault = true";
		userIdentityManager.getQuery(hql, false).executeUpdate();
		hql = "update UserIdentity set isDefault = true where id = ?";
		userIdentityManager.getQuery(hql, userIdentityId).executeUpdate();
	}

	/**
	 * 
	 * <B>方法描述：</B>（角色添加） <br/>
	 * 
	 * <B>作者： </B> 黄杰帆 <br/>
	 * 
	 * @param userIdentity
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="添加角色")
	public void roleAdd(Role role) {
		roleManager.save(role);
	}

	/**
	 * 
	 * <B>方法描述：</B>（角色修改） <br/>
	 * 
	 * <B>作者： </B> 黄杰帆 <br/>
	 * 
	 * @param role
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="修改角色")
	public void roleUpdate(Role role) {

		Role tempRole = roleManager.load(role.getId());
		tempRole.setName(role.getName());
		tempRole.setDescn(role.getDescn());
		roleManager.save(tempRole);
	}

	/***
	 * 
	 * <B>方法描述：</B>（删除角色） <br/>
	 * 
	 * <B>作者： </B> 黄杰帆 <br/>
	 * 
	 * @param idList
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="删除角色")
	public void roleDelete(List<Integer> idList) {
		List<Role> roles = roleManager.loadList(idList);
		roleManager.delete(roles);
	}

	/***
	 * 
	 * <B>方法描述：</B>（角色分配权限） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param roleId
	 * @param resourceIdList
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="分配角色权限")
	public void roleAllotResource(Integer roleId, List<Integer> resourceIdList) {

		Role role = roleManager.load(roleId);
		role.setResourcesId(resourceIdList);
		roleManager.save(role);
	}

	/***
	 * 
	 * <B>方法描述：</B>（获取所有角色信息） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param roleId
	 * @param resourceIdList
	 */
	@AjaxRpcMethod
//	@SystemServiceLog(description="获取所有用户角色")
	public List<Role> loadAllroles() {

		return roleManager.loadAll("orderId", true).getList();
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（加载角色组by id） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param id
	 * @return
	 */
	@AjaxRpcMethod
//	@SystemServiceLog(description="加载用户组")
	public Role getRole(Integer id) {
		
		Role role;
		try {
			role = roleManager.load(id);
		} catch (Exception e) {
			return null;
		}
		
		return role;
	}

	/**
	 * 
	 * <B>方法描述：</B>（用户审批） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param userId
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="审批用户")
	public void userApproval(Long userId) {
		
		User user = userManager.load(userId);
		user.setApproval(1);
		
		if(user.getIdentityId() != null) {
			UserIdentity userIdentity = userIdentityManager.load(user.getIdentityId());
			if(userIdentity != null) {
				user.setUnableScore(userIdentity.getInitScore());
			}			
		} else {
			UserIdentity userIdentity = userIdentityManager.getDefalutUserIdentity();
			if(userIdentity != null) {
				user.setIdentityId(userIdentity.getId());
				user.setUnableScore(userIdentity.getInitScore());
			}
		}
		userManager.save(user);
	}

	/**
	 * 
	 * <B>方法描述：</B>（批量用户审批） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param userList
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="批量审批用户")
	public void userApprovalList(List<Long> userList) {
		
		for(Long l :userList) {
			this.userApproval(l);
		}
	}

	/**
	 * 
	 * <B>方法描述：</B>（审批不通过） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param userId
	 */
	@AjaxRpcMethod
	@SystemServiceLog(description="不通过用户审批")
	public void userUnApproval(Long userId) {
		User user = userManager.load(userId);
		if(user != null) {
			userManager.delete(user);
		}		
	}

	/**
	 * 
	 * <B>方法描述：</B>（查询待审批用户列表） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param username
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
//	@SystemServiceLog(description="用户审批列表")
	public IPage<User> userAuditSearch(String username, Integer pageNo, Integer pageSize) {

		String hql = "from User where approval = ? and locked = ? and username like ? order by orderId asc";

		return userManager.findByQuery(hql, new Object[] { 0, false, "%" + username + "%" }).getPageByPageNo(pageNo, pageSize);
	}
	
	@AjaxRpcMethod
	public Map<Integer,Group> getGroupForId(Integer sortId) {

		Map<Integer,Group> map = Maps.newHashMap();
		
		if (sortId == null) {
			sortId = 1;
		}
		
		List<Group> list = groupManager.find("orderId", true, "sortId", sortId).getList();
		for(Group group : list){
			
			map.put(group.getId(), group);
			
		}
		
		return map;
	}

	/**
	 * 
	 * <B>方法描述：</B>（查询用户列表） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param username
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@SystemServiceLog(description="查询用户列表")
	public IPage<User> userListSearch(Integer groupId, Integer indentifyId, String username, Integer pageNo, Integer pageSize) {

		String hql = "from User where ";
		String temp = "";
		List<Object> valueList = Lists.newArrayList();
		if(groupId != null) {
			Map<Integer,Group> map = getGroupForId(groupManager.load(groupId).getSortId());
			List<Integer> gList = map.get(groupId).getChildsId();
			if(gList.size()>0){
				temp+="( ";
				for(Integer i : gList){
					temp += "parentId=? or ";
					valueList.add(i);
				}
				temp += "parentId=? ) and ";
			}else{
				temp += "parentId=? and ";
			}
			valueList.add(groupId);
		}
		if(indentifyId != null) {
			temp += "identityId=? and ";
			valueList.add(indentifyId);			
		}
		if(!Strings.isNullOrEmpty(username)) {
			temp += "(username like ? or nickname like ?)and ";
			valueList.add("%" + username + "%");			
			valueList.add("%" + username + "%");			
		}
		hql = hql + temp + "approval = ? and id > ?  order by orderId";
		valueList.add(1);
		valueList.add(2l);
		return userManager.findByQuery(hql, valueList.toArray()).getPageByPageNo(pageNo, pageSize);
	}
	
	public IPage<Map<String,Object>> userDataSearch(Integer groupId, Integer indentifyId, String username, Integer pageNo, Integer pageSize) {
		
		String hql = "select u.id,u.username,u.nickname,i.name,u.identityId,u.rolesId from User u , UserIdentity i where u.identityId=i.id and ";
		String temp = "";
		List<Object> valueList = Lists.newArrayList();
		if(groupId != null) {
			Map<Integer,Group> map = getGroupForId(groupManager.load(groupId).getSortId());
			List<Integer> gList = map.get(groupId).getChildsId();
			if(gList.size()>0){
				temp+="( ";
				for(Integer i : gList){
					temp += "u.parentId=? or ";
					valueList.add(i);
				}
				temp += "u.parentId=? ) and ";
			}else{
				temp += "u.parentId=? and ";
			}
			valueList.add(groupId);
		}
		if(indentifyId != null) {
			temp += "u.parentId=? and ";
			valueList.add(indentifyId);			
		}
		if(!Strings.isNullOrEmpty(username)) {
			temp += "u.username like ? and ";
			valueList.add("%" + username + "%");			
		}
		hql = hql + temp + "u.approval = ? and u.id > ?  order by u.orderId";
		valueList.add(1);
		valueList.add(2l);
		try {
			return userManager.findProperty(new String[]{"id","username","nickname","iendtifyName","identityId","roleIdList"}, hql, valueList.toArray()).getPageByPageNo(pageNo, pageSize);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 
	 * <B>方法描述：</B>（查询用户身份列表） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param name
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@SystemServiceLog(description="查询用户身份列表")
	public IPage<UserIdentity> userIdentityListSearch(String name, Integer pageNo, Integer pageSize) {

		String hql = "from UserIdentity";
		List<Object> valueList = Lists.newArrayList();
		if(!Strings.isNullOrEmpty(name)){
			hql+=" where name like ? ";
			valueList.add("%"+name+"%");		
		}
		return userIdentityManager.findByQuery(hql, valueList.toArray()).getPageByPageNo(pageNo, pageSize);
	
	}

	/**
	 * 
	 * <B>方法描述：</B>（查询角色列表） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param name
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@SystemServiceLog(description="查询角色列表")
	public IPage<Role> roleListSearch(String name, Integer pageNo, Integer pageSize) {

		String hql = "from Role where name like ?  order by orderId";
		return roleManager.findByQuery(hql, new Object[] { "%" + name + "%" }).getPageByPageNo(pageNo, pageSize);
	}
		
	/***
	 * 
	 * <B>方法描述：</B>（找出用户列表记录） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param List<Long> userIds
	 */
	public List<User> findUserList(List<Long> userIds) {
		
		return userManager.loadList(userIds);
	}
	
	/***
	 * 
	 * <B>方法描述：</B>（找出用户记录） <br/>
	 * 
	 * <B>作者： </B> 梁卓文 <br/>
	 * 
	 * @param Long userId
	 */
	public User findUser(Long userId) {
		
		return userManager.load(userId);
	}
	
	public UserDetail findUserDetailByUserId(Long userId){
		
		return userDetailManager.findUnique("userId", userId);
	}
	
	public IPage<User> getUserOfClassId(Integer classId, Integer pageNo, Integer pageSize){
		
		return userManager.find("parentId", classId).getPageByPageNo(pageNo, pageSize);
	}
	
	public IPage<User> getUserOfClassIWithStartNo(Integer classId, Integer startNo, Integer pageSize){
		
		return userManager.find("parentId", classId).getPageByStartNo(startNo, pageSize);
	}
	
	@AjaxRpcMethod
	@SystemServiceLog(description="设置用户部门")
	public String setUserGroup(List<Integer> idList, Integer groupId) {
		
		List<Long> longIdList = Lists.newArrayList();
		for(Integer id : idList ) {
			longIdList.add(Long.parseLong(id.toString()));
		}
		
		if(longIdList.size() == 0 || groupId == null ) {
			return "请选择用户或者部门!";
		}
		String hql = "update User set parentId = ? where id in (:idList)";
		
		userManager.getQuery(hql, groupId).setParameterList("idList", longIdList).executeUpdate();
		
		return "设置成功!";
	}
	
	@AjaxRpcMethod
//	@SystemServiceLog(description="找出所有用户")
	public List<User> loadAllUser() {
		String hql = "from User where approval = ? and id > ?  order by orderId";
		List<Object> valueList = Lists.newArrayList();
		valueList.add(1);
		valueList.add(2l);
		
		return userManager.findByQuery(hql, valueList.toArray()).getList();
	}
	
	@AjaxRpcMethod
	@SystemServiceLog(description="更新用户可用积分")
	public void updateUserScore(Long userId, Double score) {
		
		String hql = "update User set unableScore = ? where id = ? ";
		
		userManager.getQuery(hql, new Object[]{score, userId}).executeUpdate();
	}

	
	@AjaxRpcMethod
	public Map<Integer, List<Integer>> getUserIdentityToRoleIdMap(){
		try {
			Map<Integer, List<Integer>> resultMap = Maps.newHashMap();
			List<UserIdentity> userIdentityList = userIdentityManager.loadAll().getList();
		
			for(UserIdentity u:userIdentityList){
				resultMap.put(u.getId(), u.getRolesId());
			}
			return resultMap;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	@AjaxRpcMethod
	public Map<Integer, List<Integer>> getGroupToRoleIdMap(){
		try {
			Map<Integer, List<Integer>> resultMap = Maps.newHashMap();
			List<Group> groupPage = groupManager.loadAll().getList();
			for(Group group:groupPage){
				resultMap.put(group.getId(), group.getRolesId());
			}
			return resultMap;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@AjaxRpcMethod
	public List<Role> loadRoleList() {
		return roleManager.findByQuery("from Role  order by orderId").getList();

	}
	
	public Map<Integer,String> roleMap(){
		List<Role> roleList = roleManager.loadAll().getList();
		Map<Integer,String> map = Maps.newHashMap();
		for(Role r : roleList){
			map.put(r.getId(), r.getName());
		}
		return map;
					
	}
	
	public Map<Integer,String> groupMap(){
		List<Group> roleList = groupManager.loadAll().getList();
		Map<Integer,String> map = Maps.newHashMap();
		for(Group r : roleList){
			map.put(r.getId(), r.getName());
		}
		return map;
		
	}
	
	public Map<Integer,String> identifyMap(){
		List<UserIdentity> roleList = userIdentityManager.loadAll().getList();
		Map<Integer,String> map = Maps.newHashMap();
		for(UserIdentity r : roleList){
			map.put(r.getId(), r.getName());
		}
		return map;
		
	}
	
	@AjaxRpcMethod
	public boolean repeatUsername(Long id,String username){
		String hql = "from User where username=?";
		try{
			User user = userManager.findByQuery(hql,username).getList().get(0);
			if(user.getId().equals(id)){
				return true;
			}
		}catch(Exception e){
			return true;
		}
		return false;
	}


	
}
